//
//  PLBroadcaster.m
//  Plankton
//
//  Created by Marc Schlichte on 21.07.08.
//  Copyright 2008 Framework labs. All rights reserved.
//

#import "PLBroadcaster.h"


@implementation PLBroadcaster

- (id)initWithPlatform:(PLPlatform *)platform_
{
    if (self = [super init]) {
        platform = [platform_ retain];
        aid = [platform createAid];
        receivers = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)dealloc
{
    [receivers release];
    [aid release];
    [platform release];
    [super dealloc];
}

- (void)broadcast:(id)message
{
    for (NSString* receiver in receivers) {
        [platform send:[NSArray arrayWithObjects: @"broadcast", message, nil] 
                    to:receiver];
    }
}

@end

@implementation PLBroadcastReceiver

@synthesize delegate;

- (id)initWithPlatform:(PLPlatform *)platform_
{
    if (self = [super init]) {
        platform = [platform_ retain];
        ownAid = [platform createAid];
        
        receivePattern = [[PLPattern patternWithPredicateFormat:@""] retain];
        [receivePattern setMessageHandler:self];
        [platform receive:receivePattern by:ownAid];
    }
    return self;
}

- (void)dealloc
{
    [self tuneOut];
    
    [receivePattern release];
    [broadcasterAid release];
    [ownAid release];
    [platform release];
    [super dealloc];
}

- (void)tuneInto:(NSString *)aid
{
    if (![broadcasterAid isEqual:aid]) {
        [self tuneOut];
    
        broadcasterAid = [aid retain];
        if (broadcasterAid) {
            [platform send:[NSArray arrayWithObjects:@"tuneInto", ownAid, nil] 
                        to:broadcasterAid];
        }
    }
}

- (void)tuneOut
{
    if (broadcasterAid) {
        [platform send:[NSArray arrayWithObjects:@"tuneOut", ownAid, nil]
                    to:broadcasterAid];
         [broadcasterAid release];
         broadcasterAid = nil;
    }
}

- (void)handleMessage:(id)message forPattern:(PLPattern *)pattern
{
    if (delegate) {
        [delegate broadcastReceiver:self receivedMessage:message];
    }
    [platform receive:receivePattern by:ownAid];
}

@end
